package org.blogwu.learn.multithread.chapter3.demo1;

import java.util.concurrent.locks.ReentrantLock;

public class Main2 {

    public static void main(String[] args) throws InterruptedException {
        DeadLock d1 = new DeadLock(1);
        DeadLock d2 = new DeadLock(2);
        d1.start();
        d2.start();
        Thread.sleep(10000);
        d1.interrupt();
    }
}

class DeadLock extends Thread {
    static ReentrantLock reentrantLock1 = new ReentrantLock();
    static ReentrantLock reentrantLock2 = new ReentrantLock();

    int lock;

    public DeadLock(int lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        try {
            if (lock == 1) {
                reentrantLock1.lockInterruptibly();
                Thread.sleep(5000);
                System.out.println(lock + "执行完毕开始获取第二把锁");
                reentrantLock2.lockInterruptibly();
            } else {
                reentrantLock2.lockInterruptibly();
                Thread.sleep(5000);
                System.out.println(lock + "执行完毕开始获取第二把锁");
                reentrantLock1.lockInterruptibly();
            }
            System.out.println(lock + " 执行完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (reentrantLock1.isHeldByCurrentThread()) {
                System.out.println(lock + " r1释放锁");
                reentrantLock1.unlock();
            }

            if (reentrantLock2.isHeldByCurrentThread()) {
                System.out.println(lock + " r2释放锁");
                reentrantLock2.unlock();
            }
        }
    }
}
